<?php
/**
 * Moduł rejestracji
 * @author Miron Pawlik
 */

//pobieranie informacji o wszystkich przedmiotach
$subjects = $db->getData('subjects', false, 'subjectID', 'name');

$tmp = $db->query("SELECT * FROM terms AS t JOIN studentSubjects AS ss ON ss.subjectID = t.subjectID WHERE ss.indexID = ".$user->getId()." ORDER BY t.subjectID, t.day, t.timeStart, t.week");
$allTerms = $tmp->fetchAll();
$tmp->closeCursor();


//sprawdzanie czy nie zostal wyslany formularz
if($fd['send'] && $_conf['registering'] && !$user->isLocked()) {
    //sprawdzanie czy suma wag dla kazdego przedmiotu nie jest za duza
    $additionalPts = $_conf['ptsAll'];

    $arr = $fd['term'];
    foreach($arr as $key => $subject) {
        $sum = 0;
        foreach($subject as $term) {

            //$term - wybrana waga dla terminu
            //sprawdzanie czy waga jest poprawna
            if(!is_numeric($term) && $term > -2)
                $errorMsg = "Błąd wagi"; //to nie ma prawa się zdarzyć ;)
            //sprawdzamy czy przypadkiem termin nie ma wagi ujemnej
            if($term >= 0)
                $sum += $term;
            //sprawdzamy czy liczba pkt na jeden termin nie jest za duza, jesli tak to ustawiamy sume jako duza liczbe, co wygeneruje nam pozniej blad
            if($term > $_conf['ptsPerTerm']) {
                $sum = $_conf['ptsPerSub']+$additionalPts+1;
                break;
            }

        }
        if($sum > $_conf['ptsPerSub'] + $additionalPts) {
            $errorMsg = "Suma punktów dla ".$subjects[$key]." jest za duża";
            break;
        }

        if($sum < $_conf['ptsMin']) {
            $errorMsg = "Suma punktów dla ".$subjects[$key]." jest za mała";
            break;
        }
        $additionalPts -= ($sum > $_conf['ptsPerSub']) ? $sum - $_conf['ptsPerSub'] : 0;
    }
    //jestli wszystko bylo poprwanie, zapisujemy nowe preferencje studenta ...
    if(!isset($errorMsg)) {
        // ...ale najpierw usuwamy stare preferncje
        $db->deleteAll('studentTerms', 'indexID = '.$user->getId());

        foreach($allTerms as $term) {
            $wei = $fd['term'][$term['subjectID']][$term['genID']];
            $db->addNew('studentTerms', array('indexID' => $user->getId(),
                    'subjectID' => $term['subjectID'],
                    'termGenId' => $term['genID'],
                    'weight' => $wei,
                    'reason' => ($wei==-1)?$fd['reason'][$term['subjectID']][$term['genID']]:""));
        }
        $_SESSION['ok'] = true;
        $db->editById($user->getId(), 'students', array('register'=>1), 'indexId');
        header('Location: '.$_conf['host']);
        exit;
    }
    else {
        $db->addNew('errorLogs', array('indexId' => $user->getId(), 'date' => time(), 'ip' => $_SERVER["REMOTE_ADDR"], 'error' => $errorMsg));
    }
}
//blokowanie mozliwosci zmiany preferencji, jesli uzytkownik tak zdecydowal
if($fd['lock']) {
    $db->editById($user->getId(), 'students', array('locked'=>1), 'indexId');
    header('Location: '.$_conf['host']);
}

if($user->hasChooseSubjects()) {

    if(isset($errorMsg)) {
        $smarty->assign('errorMsg', $errorMsg);
    }
    $smarty->assign('showForm', ($_conf['registering'] && (!$user->isRegister() || $fd[0] == 'reg')));
    $smarty->assign('locked', $user->isLocked());
    //pobieramy zapisane terminy studenta
    if($fd[0] == 'show' && is_numeric($fd[1]) && $user->isAdmin()) {
        $query = $db->getAll('studentTerms', 'subjectID', 'indexID = '.$fd[1]);
        $smarty->assign('showForm', false);
        $smarty->assign('locked', true);
    }
    else {
        $query = $db->getAll('studentTerms', 'subjectID', 'indexID = '.$user->getId());
        if($user->isAdmin()) {
            $tmp = $db->query("SELECT subjectID , termGenId , SUM ( weight ) as sum, count ( weight ) as count FROM studentTerms WHERE weight > 0 GROUP BY subjectId , termGenId");
            $suma = $tmp->fetchAll();

            $tmp = $db->query("SELECT s.subjectID as subjectID, count(indexID) as count FROM subjects AS s JOIN studentSubjects AS ss ON ss.subjectID = s.subjectID GROUP BY s.subjectID");
            $subSum = $tmp->fetchAll();
        }
    }

    //... i przerabiamy na magiczna tabelke
    $sel = array();
    $reason = array();
    $stat = array();
    $counter = array();
    $subjectSum = array();
    if($user->isAdmin()) {
        if($suma) {
            foreach($suma as $s) {
                $stat[$s['subjectID']][$s['termGenId']] = $s['sum'];
                $counter[$s['subjectID']][$s['termGenId']] = $s['count'];
            }
            foreach($subSum as $s){
                $subjectSum[$s['subjectID']] = $s['count'];
            }
            $smarty->assign('stat', $stat);
            $smarty->assign('count', $counter);
            $smarty->assign('subjectSum', $subjectSum);
        }
    }

    foreach($query as $q) {
        $sel[$q['subjectID']][$q['termGenId']] = $q['weight'];
        $reason[$q['subjectID']][$q['termGenId']] = htmlspecialchars($q['reason']);
    }
    //var_dump($stat);
    $smarty->assign('sel', $sel);
    $smarty->assign('reason', $reason);

    //przekazujemy nazwy tygodni i dni
    $smarty->assign('week', $weeks);
    $smarty->assign('days', $days);
    $smarty->assign('hours', $hours);


    //definiujemy dostepne wagi
    $weights = range(0, $_conf['ptsPerTerm']);//
    $weights[-1] = 'niemożliwy';

    $smarty->assign('weights', $weights);
    //pobieramy wszystkie terminy
    $smarty->assign('terms', $allTerms);
}
//pierwsze uruchomienie i wybranie przedmiotow
else {
    $template = 'subjects';
    if($fd['editData']) {
        if(is_array($fd['subjects'])) {
            foreach($fd['subjects'] as $subject) {
                $db->addNew('studentSubjects', array('indexID' => $user->getId(), 'subjectID' => (int)$subject));
            }
            $db->editById($user->getId(), 'students', array('subjectsChoose'=>1), 'indexId');
            header('Location: '.$_conf['host']);
        }
    }
}

$smarty->assign('subjects', $subjects);


//sprawdzanie czy dane zostaly poprawnie zapisane
if(isset($_SESSION['ok']) && $_SESSION['ok']) {
    $_SESSION['ok'] = false;
    $smarty->assign('okMsg', true);
}
